package ru.troyanov.Datchick.util;

import org.modelmapper.ModelMapper;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import ru.troyanov.Datchick.dto.MeasurementDTO;
import ru.troyanov.Datchick.services.SensorsService;

@Component
public class SensorValidatorForMeasurement implements Validator {
    private final SensorsService sensorsService;

    public SensorValidatorForMeasurement(SensorsService sensorsService) {
        this.sensorsService = sensorsService;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return clazz.equals(MeasurementDTO.class);
    }

    @Override
    public void validate(Object target, Errors errors) {
        MeasurementDTO measurementDTO = (MeasurementDTO) target;
        String sensorName = measurementDTO.getSensorName();
        if (!sensorsService.findByName(sensorName).isPresent()) {
            errors.rejectValue("sensor", "", "The sensor you specified does not exist");
        }
    }
}
